package com.yazi.mxz.common.service.impl;

import javax.annotation.Resource;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyNoPermissionException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yazi.mxz.common.db.dao.AdDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Ad;
import com.yazi.mxz.common.service.AdService;

@Service("adService")
public class AdServiceImpl extends BasicService<Ad> implements AdService {
	private static Logger log = LoggerFactory.getLogger(AdServiceImpl.class);

	@Resource
	AdDao adDao;
	
	@Override
	protected Dao<Ad> getDao() {
		return adDao;
	}
	
	@Override
	public Ad addOrEditByStoreId(long storeId, Ad ad) throws MyException {
		Long adId = ad.getAdId();
		if (null != adId && adId > 0) {
			log.debug("addOrModifyByStoreId->modify：storeId={},adId={}", storeId, adId);
			Ad destAd = adDao.get(adId);
			if (storeId != destAd.getStoreId()) {
				throw new MyNoPermissionException();
			}
			destAd = ValueFactory.combine(ad, destAd);
			destAd.setStatus(false);
			// 根据有效期限更新有效状态
			if (destAd.getExpiredTime() > DateUtil.getTimeStamp()) {
				destAd.setStatus(true);
			}
			return adDao.merge(destAd);
		} else {
			log.debug("addOrModifyByStoreId->add：storeId={},title={}", storeId, ad.getTitle());
			ad = ValueFactory.validate(ad);
			ad.setStatus(false);
			// 根据有效期限设置有效状态
			if (ad.getExpiredTime() > DateUtil.getTimeStamp()) {
				ad.setStatus(true);
			}
			ad.setStoreId(storeId);
			ad.setAddTime(DateUtil.getTimeStamp());
			ad.setAdId(null);
			adDao.persist(ad);
			return ad;
		}

	}

	@Override
	public void removeByStoreId(long storeId, long[] adIds) {
		log.debug("removeByStoreId：storeId={},adIds={}", storeId, adIds);
		adDao.deleteByStoreId(storeId, adIds);
	}

}
